<!--
 * @Description: 
 * @Author: xuzp4
 * @Date: 2022-01-18 14:02:57
 * @LastEditors: xuzp4
 * @LastEditTime: 2022-01-19 14:28:12
 * @FilePath: \vue_demo\src\view\upload\index.vue
-->
<template>
  <el-upload
    class="upload-demo"
    ref="upload"
    action="#"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    :auto-upload="false"
    :http-request="httpRequest"
  >
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <el-button
      style="margin-left: 10px"
      size="small"
      type="success"
      @click="submitUpload"
      :loading="loading"
      >上传到服务器</el-button
    >
  </el-upload>
</template>

<script>
import $ from "jquery";
import {
  getCredentials,
  putFileOnS3,
  uploadsClient,
} from "../../service/index";
export default {
  data() {
    return {
      fileList: [],
      loading: false,
    };
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    httpRequest(param) {
      this.loading = true;
      // 获取上传文件的信息
      console.log("params", param);
      const fileObj = param.file;
      // 创建FormData 对象
      const uploadForm = new FormData();
      // 将上传文件的信息赋值给uploadForm里的file
      uploadForm.append("file", fileObj);
      uploadForm.append("name", "bbb");
      let creds = {};
      getCredentials()
        .then((credentials) => {
          creds = credentials;
          return putFileOnS3(credentials, fileObj);
        })
        .then((credentials) => {
          return uploadsClient
            .createUpload({
              tileset: `xu0430.daqingshan`,
              url: creds.url,
              name: "daqingshan",
            })
            .send();
        })
        .then(() => console.log("created Mapbox upload"))
        .catch((err) => console.log("error:", err));
    },
  },
};
</script>